import Vue from 'vue';
import Setting from '@/setting'
// 自定义权限指令
const gwPermission = {
  inserted(el, binding, vnode) {
    const { value } = binding;

    if (!value) {
      console.error('需要传入权限标识，如 v-permission="\'talent_add\'"');
      return;
    }

    // 从 sessionStorage 中获取按钮权限数据
    let btnPermissionStr = '';
    if(Setting.isMock){
      btnPermissionStr = "[" +
          "{\"action\":\"nd_expert_add\",\"describe\":\"新增\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_edit\",\"describe\":\"编辑\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_check\",\"describe\":\"审核\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_delete\",\"describe\":\"删除\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_import\",\"describe\":\"导入\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_examine\",\"describe\":\"查看数据标准\",\" type\":\"1\"}," +
          "{\"action\":\"nd_expert_statistics\",\"describe\":\" 统计图表\",\" type\":\"1\"}," +
          "{\"action\":\"nd_fruit_add\",\"describe\":\" 成果新增\",\" type\":\"1\"}," +
          "{\"action\":\"nd_fruit_edit\",\"describe\":\" 成果编辑\",\" type\":\"1\"}," +
          "{\"action\":\"nd_fruit_delete\",\"describe\":\" 成果删除\",\" type\":\"1\"}," +
          "{\"action\":\"nd_fruit_check\",\"describe\":\" 成果审核\",\" type\":\"1\"}" +
        "]";
    }else{
      btnPermissionStr = window.sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH');
      console.log("window.sessionStorage====获取到的权限标识"+btnPermissionStr);
    }

    // 安全地解析权限数据，处理 null 或无效 JSON 的情况
    let btnPermission = [];
    try {
      if (btnPermissionStr) {
        const parsed = JSON.parse(btnPermissionStr);
        // 确保解析结果是数组
        if (Array.isArray(parsed)) {
          btnPermission = parsed;
        } else {
          console.warn('权限数据格式不正确，应该是数组格式');
        }
      }
    } catch (e) {
      console.error('解析权限数据失败:', e);
    }

    // 检查权限
    const hasPermission = btnPermission.some(permission => permission && permission.action === value);
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el);
    }
  }
};
// 注册全局指令
Vue.directive('gwPermission', gwPermission);

export default gwPermission;
